//#define __FORCE_TRACE__
//#define __FORCE_DEBUG__
//#define __FORCE_INFO__
#define THIS_FILE "ioc\handlerAdd.sqf"
#include <core_macros.h>

TRACE_1("Start",_this);

private ["_unique_id","_namespace","_event","_idx","_evt_idx","_events","_handler","_event_handlers","_namespace_handlers","_handler_idx"];
_unique_id = "";
_namespace = "";
_event = "";
_handler = "";
if (count _this > 3) then {
	DEFAULT_PARAM(_unique_id,0,"");
	DEFAULT_PARAM(_namespace,1,"");
	DEFAULT_PARAM(_event,2,"");
	DEFAULT_PARAM(_handler,3,"");
} else {
	DEFAULT_PARAM(_namespace,0,"");
	DEFAULT_PARAM(_event,1,"");
	DEFAULT_PARAM(_handler,2,"");
};

_handler_idx = -1;
if (IS_STRING(_namespace) && IS_STRING(_event) && IS_STRING(_handler) && IS_STRING(_unique_id) && {_namespace != ""} && {_event != ""} && {_handler != ""}) then {
	_events = [];
	_event_handlers = [];
	_idx = GVAR(NAMESPACES) find toLower(_namespace);
	if (_idx <= 0) then {
		TLOG_1("Adding unregistered namespace",_namespace);
		[_namespace] call FUNC(register);
		_idx = GVAR(NAMESPACES) find toLower(_namespace);
	};
	if (_idx >= 0) then {
		TRACE_1("Existing Namespace",_idx);
		_events = GVAR(EVENTS) select _idx;
		_namespace_handlers = (GVAR(HANDLERS) select _idx);
		_evt_idx = _events find toLower(_event);
		if (_evt_idx >= 0) then {
			TRACE_1("Existing Event",_idx);
			_event_handlers = _namespace_handlers select _evt_idx
		} else {
			TRACE_1("New Event",_this);
			_evt_idx = count(_events);
			_events set [_evt_idx,toLower(_event)];
			GVAR(EVENTS) set [_idx,_events];
		};
		TRACE_1("Event Handlers",_event_handlers);
		_handler_idx = count _event_handlers;
		if (_unique_id == "") then {
			_unique_id = format [QGVAR(%1_%2_%3),_idx,_event,_handler_idx];
		};
		_event_handlers set [_handler_idx,[_unique_id,_handler]];
		_namespace_handlers set [_evt_idx, _event_handlers];
		GVAR(HANDLERS) set [_idx, _namespace_handlers];
	} else {
		TRACE_1("Invalid Namespace",_this);
	};
} else {
	TRACE_1("Invalid Event Handler",_this);
};
TRACE_1("End",ARR_2(_unique_id,_handler_idx));
_unique_id;